from FPDLCore.BaseClientNet import BaseClientNet
from FPDLCore import MessageDefs

class EntryClient(BaseClientNet):
    def __init__(self, remoteaddr, sel, filepath, onentry):
        BaseClientNet.__init__(self, remoteaddr, sel)
        self.filepath = filepath
        self.onentry = onentry
        self.data = None

    def onconnectionmade(self, conn):
        self.send(MessageDefs.GetWorkerInfoRequest(self.filepath))

    def onconnectionfail(self, conn):
        print("EntryClient: Connect to entry server fialed, retry...")
        self.connect()

    def onread(self, conn, data):
        if self.data:
            data = self.data + data
        response = MessageDefs.deserialize(data)
        if response:
            print("Entry server respond:", response)
            self.onentry(response)
            self.data = None
            self.close()
        else:
            self.data = data

    def onsend(self, conn):
        pass

    def onclose(self, conn):
        pass
